// pages/details-goods/details-goods.js
const apiurl = require('../../config').apiurl;
var WxParse = require('../../wxParse/wxParse.js');
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc();
Page({
  showShare(e) {
    var goods_id = e.currentTarget.dataset.shareid
    pulibc.navigateUrl('../share/share?id=' + goods_id);
  },
  // 显示购物车
  showCart() {
    // console.log(123)
    wx.reLaunch({
      url: '../cart/cart'
    })
  },
  // 返回到首页
  showIndex() {
    wx.reLaunch({
      url: '../index/index'
    })
  },

  /**
   * 页面的初始数据
   */
  data: {
    tabDetails: true,
    dataVal: {},
    // quantity:1,
    cartOne: true,
    goods_id: '',
    cartList: [],
    cart_id: 0,
    hideShopPopup: true,
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    buyNumber: 0, //初始化购买数量
    buyNumMin: 1, //设置最小购买数量为1
    buyNumMax: 10, //设置最大购买数量为10,
    id: '', //设置传入提交订单页的参数,
    buyNow: false,
    goods_num: 0, //已购买的商品数量
    member_info: {}
  },
  // tab栏切换
  chengTab() {
    this.setData({
      tabDetails: false
    })
  },
  chengDetalis() {
    this.setData({
      tabDetails: true
    })
  },

  // 获取用户信息
  getUserInfo() {
    let url = apiurl + '/member/index';
    let key = wx.getStorageSync("key")
    wx.request({
      url: url,
      data: {
        key
      },
      success: data => {
        console.log('会员', data)
        if (data.data.code == 200) {
          let member_info = data.data.datas.member_info
          console.log('会员', member_info)
          this.setData({
            member_info
          })
        }else if(data.data.code == 400){
          pulibc.navigateUrl('../register/register')
        }

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    var id = options.id;
    this.setData({
      goods_id: id
    })
    this.getGoodsDetail(id);
    this.getCartData();
  },
  //商品详情
  getGoodsDetail(id) {
    let url = apiurl + '/goods/info';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.goods_id = id;
    wx.request({
      url: url,
      data: params,
      success: data => {
        console.log(data)
        if (data.data.code == 200) {
          let dataVal = data.data.datas.info
          console.log("dataVal", dataVal)
          WxParse.wxParse('article', 'html', dataVal.goods_body, this);
          this.setData({
            dataVal,
            buyNumber: dataVal.goods_storage >= 1 ? 1 : 0, //判断库存是否大于1
            buyNumMax: dataVal.goods_storage //最大购买数
          })
        }

      }
    })
  },
  // 立即购买
  buyNow() {
    let id = this.data.goods_id + '|' + this.data.buyNumber;
    this.closePopupTap();
    pulibc.navigateUrl('../to-pay-order/to-pay-order?id=' + id);

  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  tobuy: function() {
    // 库存不足时返回
    if (this.data.buyNumber == 0) {
      return;
    }
    this.setData({
      shopType: "tobuy"
    });
    this.bindGuiGeTap();
  },
  toAddShopCar: function() {
    // 库存不足时返回
    if (this.data.buyNumber == 0) {
      return;
    }
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  // 规格弹窗隐藏
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },
  // 购买数量
  numJianTap: function() {
    var currentNum = this.data.buyNumber;
    if (currentNum <= this.data.buyNumMin) {
      return;
    }
    currentNum--;
    this.setData({
      buyNumber: currentNum
    })

  },
  numJiaTap: function() {
    var currentNum = this.data.buyNumber;
    if (currentNum >= this.data.buyNumMax) {
      return;
    }
    currentNum++;
    this.setData({
      buyNumber: currentNum
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }else {
      this.getUserInfo();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  addShopCar(e) {
    // console.log(123)
    console.log(e)
    var url = apiurl + '/membercart/cart_add'
    var key = wx.getStorageSync('key')
    var goods_id = this.data.goods_id;
    var quantity = this.data.buyNumber;

    wx.request({
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      url: url,
      method: 'POST',
      data: {
        key,
        goods_id,
        quantity
      },
      success: res => {
        console.log(res)
        if (res.data.code == 200) {
          wx.removeStorageSync('cartList');
          this.getCartData();
          this.closePopupTap();
          pulibc.showToast('加入购物车成功', 'success');
        } else if (res.data.datas.error == "商品已存在购物车") {
          wx.removeStorageSync('cartList');
          this.closePopupTap();
          let goods_num = this.data.goods_num;
          let buyNumber = this.data.buyNumber;
          let quantity = goods_num + buyNumber;
          this.editCartData(quantity);
          this.getCartData();
        }
      }
    })


  },
  // 二次加入购物车
  editCartData(quantity) {
    let url = apiurl + '/membercart/cart_edit_quantity';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = this.data.cart_id;
    params.quantity = quantity;
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success(res) {
        console.log(res)
        if (res.data.code == 200) {
          pulibc.showToast('加入购物车成功', 'success');
        } else {
          pulibc.showToast(res.data.datas.error, 'none');
        }
      }
    })
  },
  getCartData() {
    var url = apiurl + '/membercart/cart_list';
    var key = wx.getStorageSync('key')
    wx.request({
      url: url,
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        key
      },
      success: res => {
        if (res.data.code == 200) {
          var cartList = res.data.datas.cart_list;
          this.setData({
            cartList
          })
        }
        // 筛选出要加入购物车的cart_id
        this.data.cartList.map(item => {
          if (item.goods_id == this.data.goods_id) {
            this.setData({
              cart_id: item.cart_id,
              goods_num: item.goods_num
            })
          }
        })
        console.log(this.data.cartList, this.data.cart_id)
      }
    })
  }
})